const express = require("express");
const socketio = require("socket.io");
const http = require("http");

const app = express();
const server = http.createServer(app);
const io = socketio(server);

// 存储在线用户
const onlineUsers = new Map(); // 使用 Map 来存储用户名和 socket.id 的映射

// 静态文件服务
app.use(express.static("public"));

// Socket.io连接处理
io.on("connection", (socket) => {
  console.log("新用户连接");

  // 处理用户名设置
  socket.on("set username", (username) => {
    if (onlineUsers.has(username)) {
      socket.emit("username exists");
    } else {
      onlineUsers.set(username, socket.id);
      socket.username = username;
      socket.emit("username set", username);
      io.emit("user joined", username);
      io.emit("update users", Array.from(onlineUsers.keys()));
    }
  });

  // 处理聊天消息
  socket.on("chat message", (msg) => {
    io.emit("chat message", { user: socket.username, message: msg });
  });

  // 处理断开连接
  socket.on("disconnect", () => {
    if (socket.username) {
      onlineUsers.delete(socket.username);
      io.emit("user left", socket.username);
      io.emit("update users", Array.from(onlineUsers.keys()));
    }
  });
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});
